package br.mikhas.util.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * Implementation of {@link ResultSetExtrator} that extracts the data on result
 * set into a {@link List} of mapped rows.
 * <p>
 * This implementation uses a {@link RowMapper} to map each row of the result
 * 
 * @author n068815 - Mikhail Domanoski
 * 
 */
public class RowMapperResultSetExtrator<T> implements ResultSetExtrator<List<T>> {

	/**
	 * The row mapper used to map each row
	 */
	private final RowMapper<T>	rowMapper;

	/**
	 * Default constructor which a {@link RowMapper} must be supplied
	 * 
	 * @param mapper The {@link RowMapper} used to map {@link ResultSet} rows
	 */
	public RowMapperResultSetExtrator(RowMapper<T> mapper) {
		this.rowMapper = mapper;
	}

	/**
	 * Extract all data on result set iterating it and mapping with the row
	 * mapper
	 */
	public List<T> extractData(ResultSet rs) throws JdbcException {
		List<T> result;

		result = new ArrayList<T>();

		int index = 0;
		T entity;

		// Maps the query
		try {
			while (rs.next()) {
				try {
					entity = this.rowMapper.mapRow(index, rs);

					// Do not add null stuff since it not useful
					if (entity != null) {
						result.add(entity);
					}

					index++;
				} catch (Exception e) {
					throw new RowMappingException("Error while mapping result set row #" + index, e);
				}
			}
		} catch (SQLException e) {
			throw new RowMappingException("Error while extracting result set data");
		}

		return result;
	}
}
